# -*- coding: utf-8 -*-
"""
   Copyright (C) 2011 Miguel de Dios

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   higher any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
"""

from Util import *
from Frontend import *
import math, os
from pprint import *

class ListFullScreen_mode:
	fons_size_small = 15
	font_size = 30
	font_size_big = 36
	fontname = 'Arial'
	margin_between_roms = 10
	vertical_distance_between_roms = font_size + margin_between_roms
	
	
	def __init__(self, util_param = None, frontend_param = None):
		self.util = util_param
		self.background = None
		self.frontend = frontend_param
		self.frontend.create_default_background()
	
	
	def check_background(self, select_rom):
		pass
	
	
	def paint_background(self):
		"""Paint the background screen-centered"""
		screen_width = self.util.options["screen_width"]
		screen_height = self.util.options["screen_height"]
		background_y = (screen_height - self.background.get_height()) / 2
		background_x = (screen_width - self.background.get_width()) / 2
		self.frontend.screen.blit(self.background, (background_x, background_y))
	
	
	def paint_list_roms(self, select_rom):
		screen_width = self.util.options["screen_width"]
		screen_height = self.util.options["screen_height"]
		count_roms = len(self.frontend.list_roms)
		
		middle_y_pos = (screen_height - self.font_size) / 2
		
		#Set the space for the top status bar
		middle_y_pos += 20
		small_arialFont = pygame.font.SysFont(self.fontname, self.fons_size_small)
		tempImage = small_arialFont.render("Mode: " + self.frontend.list_modes[self.frontend.current_mode].upper() + \
			" Listed " + str(count_roms) + " roms", False, (255, 255, 255))
		self.frontend.screen.blit(tempImage, (2, 2))
		
		arialFont = pygame.font.SysFont(self.fontname, self.font_size)
		arialFont_bold = pygame.font.SysFont(self.fontname, self.font_size_big, bold = True)
		
		#TODO optimize this sentence
		ordened_list_roms = self.frontend.list_roms[select_rom:] + self.frontend.list_roms[:select_rom]
		
		count_roms_show_middle_screen = middle_y_pos / self.vertical_distance_between_roms
		
		if count_roms_show_middle_screen > count_roms/2:
			list_roms_middle_to_bottom = ordened_list_roms[:count_roms / 2]
			list_roms_middle_to_top = ordened_list_roms[count_roms / 2:]
		else:
			list_roms_middle_to_bottom = ordened_list_roms[:count_roms_show_middle_screen]
			list_roms_middle_to_top = ordened_list_roms[-count_roms_show_middle_screen:]
		
		list_roms_middle_to_top.reverse()
		
		y = middle_y_pos
		first = True
		for rom in list_roms_middle_to_bottom:
			if first:
				size = arialFont_bold.size(rom[1])
				x = (screen_width - size[0]) / 2
				color = (255, 255, 0)
				tempImage =  arialFont_bold.render(rom[1], False, color)
				tempImage.set_alpha(255)
			else:
				size = arialFont.size(rom[1])
				x = (screen_width - size[0]) / 2
				color = (255, 255, 255)
				tempImage =  arialFont.render(rom[1], False, color)
				tempImage.set_alpha(128)
			tempImage.convert_alpha()
			#tempImage.set_alpha(255 * 0.75)
			if first:
				self.marquesine_rom_name(select_rom, x, y, tempImage)
			else:
				self.frontend.screen.blit(tempImage, (x, y))
			y +=self.vertical_distance_between_roms
			
			first = False
		
		y = middle_y_pos - self.vertical_distance_between_roms
		for rom in list_roms_middle_to_top:
			size = arialFont.size(rom[1])
			x = (screen_width - size[0]) / 2
			color = (255, 255, 255)
			tempImage =  arialFont.render(rom[1], False, color)
			tempImage.set_alpha(128)
			tempImage.convert_alpha()
			#tempImage.set_alpha(255 * 0.75)
			self.frontend.screen.blit(tempImage, (x, y))
			y -=self.vertical_distance_between_roms
	
	
	#Static vars
	offset_text = 0.0
	offset_text_dir = "right"
	last_select_rom = False
	def marquesine_rom_name(self, select_rom, x, y, textImage):
		if self.util.options["screen_width"] < textImage.get_width():
			
			if select_rom is not self.last_select_rom:
				self.last_select_rom = select_rom
				self.offset_text = 0.0
				self.offset_text_dir = "right"
			
			max_offset = textImage.get_width() - self.util.options["screen_width"]
			if self.offset_text_dir == "left":
				self.offset_text -= 40.0 / self.frontend.framesPerSecond
				if (-self.offset_text) > (max_offset / 2):
					self.offset_text_dir = "right"
			else:
				self.offset_text += 40.0 / self.frontend.framesPerSecond
				if self.offset_text > (max_offset / 2):
					self.offset_text_dir = "left"
			
			self.frontend.screen.blit(textImage, (x + self.offset_text, y))
			
		else:
			self.frontend.screen.blit(textImage, (x, y))
	
	
	def check_limits_select_rom(self, select_rom):
		if -(select_rom) == len(self.frontend.list_roms):
			select_rom = 0
		if select_rom == len(self.frontend.list_roms):
			select_rom = 0
		return select_rom
	
	
	def run(self):
		time_hold_button = 0
		
		select_rom = self.check_limits_select_rom(self.util.load_value_db("internal_selected_rom", 0))
		exit_var = False
		
		last_pressed_key = None
		last_rom = None
		last_time_move = 0
		sleep_when_pressed_same_key = 800
		change_direction = False
		
		while not exit_var:
			now = pygame.time.get_ticks()
			
			if self.util.options['shutdown_hold_button']:
				if time_hold_button:
					if ((now - time_hold_button) / 1000) > 1:
						self.frontend.show_shutdown_message()
						#If the computer does not shutdown maybe the
						#user stoped to hold the button
						#reset all flags and time counters
						time_hold_button = 0
			
			if last_pressed_key is None:
				id_rom_screensaver = self.frontend.screen_saver()
				
				if id_rom_screensaver:
					select_rom = self.frontend.translate_idrom_to_arraykey(id_rom_screensaver)
					
					self.frontend.execute_rom(select_rom)
			else:
				self.frontend.reset_screen_saver()
			
			self.frontend.screen.fill((0, 0, 0))
			
			select_rom = self.check_limits_select_rom(select_rom)
			if select_rom != last_rom:
				self.background = self.frontend.load_snap(select_rom)
				last_rom = select_rom
			elif self.background == self.frontend.default_background and last_pressed_key == K_RETURN:
				#Check if have a screenshot of rom that haven't screenshot before.
				self.background = self.frontend.load_snap(select_rom)
			
			self.paint_background()
			self.paint_list_roms(select_rom)
			
			ekey = self.frontend.get_events()
			if ekey < 0:
				ekey = -ekey
				if ekey == K_1 or ekey == K_RETURN:
					if self.util.options['shutdown_hold_button']:
						time_hold_button = (now - time_hold_button) / 1000
						if time_hold_button < 5:
							time_hold_button = 0
							self.frontend.execute_rom(select_rom)
					else:
						self.frontend.execute_rom(select_rom)
				last_pressed_key = None
				last_time_to_wait_move = now
			elif ekey > 0:
				last_pressed_key = None
				if ekey == K_ESCAPE:
					exit_var = True
				elif ekey == K_q:
					self.frontend.can_shutdown = False
					exit_var = True
				elif ekey == K_UP:
					if last_pressed_key != ekey:
						select_rom -= 1
						sleep_when_pressed_same_key = 800
						last_time_move = now
						change_direction = True
				elif ekey == K_DOWN:
					if last_pressed_key != ekey:
						select_rom += 1
						sleep_when_pressed_same_key = 800
						last_time_move = now
						change_direction = True
				elif ekey == K_RIGHT:
					if last_pressed_key != ekey:
						select_rom += 10
						select_rom %= len(self.frontend.list_roms)
						sleep_when_pressed_same_key = 800
						last_time_move = now
						change_direction = True
				elif ekey == K_LEFT:
					if last_pressed_key != ekey:
						select_rom -= 10
						select_rom %= len(self.frontend.list_roms)
						sleep_when_pressed_same_key = 800
						last_time_move = now
						change_direction = True
				elif ekey == K_1 or ekey == K_RETURN:
					time_hold_button = now
				elif ekey == K_c or ekey == K_LALT:
					# New feature: add/remove from favorities
					force_update = 1
					select_rom = self.frontend.toggle_fav(select_rom)
					self.global_count_roms = len(self.frontend.list_roms)
				elif ekey == K_SPACE:
					# New feature: show favorities or full list rom
					select_rom = self.frontend.switch_mode(select_rom)
					self.global_count_roms = len(self.frontend.list_roms)
					force_update = 1
				
				last_pressed_key = ekey
			
			if (last_pressed_key is not None) and (not change_direction):
				if (sleep_when_pressed_same_key + last_time_move) < now:
					if last_pressed_key == K_DOWN:
						select_rom += 1
					elif last_pressed_key == K_UP:
						select_rom -= 1
					#Acelerate the movement across the list
					if sleep_when_pressed_same_key > 100:
						sleep_when_pressed_same_key -= 100
					last_time_move = now
			change_direction = False
			self.frontend.waitFrame()
			pygame.display.update()